package com.spica.spicaschool.utils

import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.channels.FileChannel
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


object MD5Utils {

    /**
     * 将文件HASH
     */
    @JvmStatic
    fun encryptMD5File2String(file: File): String {
        val bs = encryptMD5File(file)
        return if (bs != null) {
            bytes2HexString(bs)
        } else ""
    }

    @JvmStatic
    private fun encryptMD5File(file: File): ByteArray? {
        var fis: FileInputStream? = null
        try {
            fis = FileInputStream(file)
            val channel = fis.channel
            val buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length())
            val md = MessageDigest.getInstance("MD5")
            md.update(buffer)
            return md.digest()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            fis?.close()
        }
        return null
    }

    private val HEX_DIGITS = charArrayOf(
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F'
    )

    @JvmStatic
    private fun bytes2HexString(bytes: ByteArray): String {
        val ret = CharArray(bytes.size shl 1)
        var i = 0
        var j = 0
        while (i < bytes.size) {
            ret[j++] = HEX_DIGITS[bytes[i].toInt() ushr 4 and 0x0f]
            ret[j++] = HEX_DIGITS[bytes[i].toInt() and 0x0f]
            i++
        }
        return String(ret)
    }
}